from cryptography.exceptions import InvalidTag
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os

from app.envConfig import ENV_CONFIG
from app.utils.exceptions import InvalidTokenError

aes_gcm_key = bytes.fromhex(ENV_CONFIG.AES_GCM_SECRET_KEY)
fernet_key = ENV_CONFIG.FERNET_SECRET_KEY.encode()


def encrypt_data(plaintext: str) -> bytes:
    aesgcm = AESGCM(aes_gcm_key)
    nonce = os.urandom(12)  # 随机生成12字节 Nonce
    ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)
    return nonce + ciphertext  # 合并 Nonce 和密文


def decrypt_data(ciphertext: bytes) -> str:
    try:
        aesgcm = AESGCM(aes_gcm_key)
        nonce = ciphertext[:12]  # 分离 Nonce
        ciphertext_body = ciphertext[12:]
        plaintext = aesgcm.decrypt(nonce, ciphertext_body, None)
        return plaintext.decode()
    except InvalidTag as e:
        raise InvalidTokenError({"o-facingMsg": "解密失败"}) from e


def encrypt_session(plaintext):
    cipher = Fernet(fernet_key)
    return cipher.encrypt(plaintext.encode()).decode()


def decrypt_session(ciphertext):
    try:
        cipher = Fernet(fernet_key)
        return cipher.decrypt(ciphertext.encode()).decode()
    except InvalidToken as e:
        raise InvalidTokenError({"o-facingMsg": "解密失败"}) from e
